package com.fms.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fms.result.ResultData;
import com.fms.dto.DashboardDto;
import com.fms.mapper.OrderDetailMapper;
import com.fms.mapper.ProductMapper;
import com.fms.mapper.ProductOrderMapper;
import com.fms.mapper.SysUserMapper;
import com.fms.entity.Product;
import com.fms.entity.ProductOrder;
import com.fms.entity.SysUser;
import com.fms.service.ProductService;
import com.fms.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.StandardMultipartHttpServletRequest;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
@CrossOrigin
@RequestMapping("/api")
@RequiredArgsConstructor
//媒体Api接口类(未使用useless)
public class ApiController {
    public static String filetype = "";
    private final  ProductOrderMapper productOrderMapper;
    private final OrderDetailMapper orderDetailMapper;
    private final SysUserMapper sysUserMapper;
    private final SysUserService sysUserService;
    private final ProductService productService;
    private final ProductMapper productMapper;
    @PostMapping("/userImage")
    public void updateUserImage(StandardMultipartHttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        System.out.println(request.getMethod());
        String update = update(request);
        System.out.println(update);
    }

    @PostMapping("/productImage")
    public void updateProductImage(StandardMultipartHttpServletRequest request) throws IOException {
        //默认地址
        String baseUrl = "E:/FurnitureManager/furniture_-manager/clientSide/public/";
        String picUrl = "demo/images/product/";
        String id = "";

        //获取文件
        Map<String, MultipartFile> fileMap = request.getFileMap();
        for (String filename : fileMap.keySet()) {
            id = filename;
        }
        MultipartFile multipartFile = fileMap.get(id);

        String imgType = multipartFile.getOriginalFilename();
        String type = imgType.substring(imgType.lastIndexOf("."));
        //写入文件
        byte[] bytes = multipartFile.getBytes();
        String filePath = baseUrl+picUrl+ id +type;
        Files.write(Paths.get(filePath), bytes);
        //更新数据
        LambdaQueryWrapper<Product> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Product::getId, id);
        Product product = new Product();
        product.setImage(picUrl+ id +type);
        productService.update(product,queryWrapper);
        filetype = type;
    }

    @GetMapping("/dashboardDetails")
    public ResultData getDataDetails(){
        DashboardDto dashboardDetails = getDashboardDetails();
        return ResultData.success(dashboardDetails);
    }

    @GetMapping("/bestSells")
    public ResultData getBestSells(){
        List<Product> list = productMapper.getBestSells();
        return ResultData.success(list);
    }

    @PostMapping("/test")
    private ResultData test(@RequestParam("file") MultipartFile[] files, @RequestHeader("Authorization") String token){
        String baseUrl = "E:/FurnitureManager/furniture_-manager/clientSide/public/";
        String picUrl = "demo/images/testPic/";
        System.out.println(token);
        for(MultipartFile file : files){
            uploadImage(token, file,baseUrl+picUrl);
        }
        return ResultData.success();
    }

    //获取数据总览(Useless)
    private DashboardDto getDashboardDetails(){
        LambdaQueryWrapper<ProductOrder> productOrderQuery = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<SysUser> sysUserQuery = new LambdaQueryWrapper<>();
        DashboardDto dto = new DashboardDto();
        Long orderCount = productOrderMapper.selectCount(productOrderQuery);
        Integer newOrder = productOrderMapper.getNewOrder();
        Double prizeCount = orderDetailMapper.getAllPrize();
        Long memberCount = sysUserMapper.selectCount(sysUserQuery);
        Integer newUserCount = sysUserMapper.getNewUserCount();
        dto.setOrderCount(orderCount).setPrizeCount(prizeCount).setMemberCount(memberCount).setNewUserCount(newUserCount).setNewOrder(newOrder);
        return dto;
    }

    private String update(StandardMultipartHttpServletRequest request) throws IOException {

        String baseUrl = "E:/FurnitureManager/furniture_-manager/clientSide/public/";
        String picUrl = "demo/images/sysUser/";
        String name = "";

        Map<String, MultipartFile> fileMap = request.getFileMap();
        for (String filename : fileMap.keySet()) {
            name = filename;
        }

        MultipartFile multipartFile = fileMap.get(name);
        String imgType = multipartFile.getOriginalFilename();
        String type = null;
        if (imgType != null) {
            type = imgType.substring(imgType.lastIndexOf("."));
        }
        byte[] bytes = multipartFile.getBytes();
        String filePath = baseUrl+picUrl+name+type;
        Files.write(Paths.get(filePath), bytes);
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUsername,name);
        SysUser sysUser = new SysUser();
        sysUser.setImgUrl(picUrl+name+type);
        sysUserService.update(sysUser,queryWrapper);
        return "img upload";
    }

    //测试通用上传图片
    public ResultData uploadImage(String id, MultipartFile file, String folder) {
        // 上传为空返回提示
        if (file == null) {
            return ResultData.error("请选择要上传的图片!");
        }
        // 上传图片超过限制返回提示
        if (file.getSize() > 1024 * 1024 * 10) {
            return ResultData.error("文件大小不能大于10M!");
        }
        // 获取文件后缀
        String suffix = Objects.requireNonNull(file.getOriginalFilename())
                .substring(file.getOriginalFilename().lastIndexOf('.') + 1, file.getOriginalFilename().length());
        if (!"jpg,jpeg,gif,png".toUpperCase().contains(suffix.toUpperCase())) {
            return ResultData.error("请选择jpg,jpeg,gif,png格式的图片!");
        }
        File savePathFile = new File(folder);
        if (!savePathFile.exists()) {
            // 若不存在该目录，则创建目录
            savePathFile.mkdir();
        }
        // 通过UUID生成文件名
        //String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + suffix;
        String fileName = id+"-"+ System.currentTimeMillis() + "-" + Math.random()+ "." + suffix;
        try {
            FileUtils.copyInputStreamToFile(file.getInputStream(), new File(folder + fileName));
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.error("保存文件出现异常!");
        }
        // 向前台返回文件名
        return ResultData.success(folder + fileName);
    }
}
